import { Mongo } from 'meteor/mongo';
import { Factory } from 'meteor/dburles:factory';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';

class UsersCollection extends Mongo.Collection {
  insert(doc, callback) {
    const ourDoc = doc;
    ourDoc.createdAt = ourDoc.createdAt || new Date();
    const result = super.insert(ourDoc, callback);
    return result;
  }
  update(selector, modifier) {
    const result = super.update(selector, modifier);
    return result;
  }
  remove(selector) {
    const result = super.remove(selector);
    return result;
  }
}

export const Users = new UsersCollection('users_fp');

// Deny all client-side updates since we will be using methods to manage this collection
Users.deny({
  insert() { return true; },
  update() { return true; },
  remove() { return true; },
});

Users.schema = new SimpleSchema({
  userId: {
    type: String,
  },
  title: {
    type: String,
    max: 100,
  },
  desc: {
    type: String,
    max: 1000,
    optional: true,
  },
  balance:{
    type: Number,
    min: 0,
  },
  createdAt: {
    type: Date,
  },
  createdBy:{
    type: String,
    optional: true,
  },
  modifiedAt:{
    type: Date,
    optional: true,
  },  
  modifiedBy:{
    type: String,
    optional: true,
  },
  //status可以枚举：已认证、待认证、禁用 
  //modify by jiangbuyun
  status:{
    type: String,
    optional: true,
  },
  //utype字段标识用户的类型，枚举：用户、项目
  //交易分为两个类别，
  //1.用户转账给项目，此时需要判断，确认对方是项目，状态为已认证时才可以交易
  //2.项目可以转给任意账号，但是账号的状态为已认证
  //add by jiangbuyun
  utype:{
    type: String,
    optional: true,
  },
  tags:{ 
    type: String,
    optional: true,
  },
  avatar:{ 
    type: String,
    optional: true,
  },
  av:{ 
    type: String,
    optional: true,
  },
});

Users.attachSchema(Users.schema);

Users.publicFields = {
  userId: 1,
  title: 1,
  desc: 1,
  createdAt: 1,
  createdBy: 1,
  modifiedAt: 1,
  modifiedBy: 1,
  status: 1,
  //add by jiangbuyun
  utype: 1,
  tags: 1,
  avatar: 1,
  balance: 1,
};

Factory.define('user', Users, {
  title: () => faker.lorem.sentence(),
  createdAt: () => new Date(),
});



if (Meteor.isServer) {
  // This code only runs on the server
  Meteor.publish('users_fp', function usersPublication() {
    return Users.find();
  });
}